package com.nxp.nfc_demo.fragments;

import android.net.http.SslError;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.fragment.app.Fragment;

import com.nxp.NFC2COM.R;
import com.nxp.nfc_demo.activities.MainActivity;
import com.nxp.nfc_demo.adapters.AndroidSystemInfo;

import cn.smartfire.unit.Util;

public class WebViewFragment extends Fragment{

	public static Handler mHandler;
	protected final static String Clean_KEY = "cleanLCDs";
	protected final static String modify_KEY = "s5625dd";//自定义显示
	protected final static String String_key = "sdfsdfsd3223";
	
	protected final static String JUDGE_KEY = "is_recevied";
	protected final static String PROXIMITY_KEY = "is_Proximity";
	protected final static String move_KEY = "notmovedown";
	protected final static String DATA_KEY = "uartnfc_data2233";
	protected final static String DATA_LENKEY = "DATALEN123654";

	protected final static String WEBDATA_SEND = "webData_send";
	protected final static String TAG_ID="tagId";
	private WebView webView;
   protected Util mUtil = new Util();

	public static void sendNFCProximityEvent(Tag tag) {
		Bundle bundle = new Bundle();
		bundle.putBoolean(PROXIMITY_KEY, true);
		bundle.putByteArray(TAG_ID,tag.getId());
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}
	public static void displaynomove(String datarate)
	{
		//rf_datarateCallback.setText(datarate);
		Bundle bundle = new Bundle();
		bundle.putByteArray(DATA_KEY, datarate.getBytes());
		bundle.putBoolean(JUDGE_KEY, false);
		bundle.putBoolean(move_KEY,true );
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);

	}
	private void setupWebView() {
		// 在WebView初始化前调用
		webView.clearCache(true);
		webView.clearHistory();

		WebSettings settings = webView.getSettings();

		// 基础设置
		settings.setJavaScriptEnabled(true);
		settings.setDomStorageEnabled(true);
		settings.setLoadWithOverviewMode(true);
		settings.setUseWideViewPort(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);

		// 解除安全限制
		settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 允许HTTPS加载HTTP资源
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
			settings.setMediaPlaybackRequiresUserGesture(false); // 允许自动播放媒体
		}
		// 解决Android 5.0+混合内容问题
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}
		// 客户端设置
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
				view.loadUrl(request.getUrl().toString());
				return false;
			}
			@Override
			public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
				Log.e("WEBVIEW", "加载错误: " + error.getDescription());
			}
			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed(); // 忽略SSL证书错误（仅限测试环境！）
			}
		});

		webView.setWebChromeClient(new WebChromeClient());

		// 添加JS接口
		webView.addJavascriptInterface(new AndroidSystemInfo(), "AndroidSystem");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			WebView.setWebContentsDebuggingEnabled(true);
		}
	}
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				processData(msg);
				super.handleMessage(msg);
			}
		};


	}
	protected void processData(Message msg) {
		Bundle bundle = msg.getData();

		boolean sdf = bundle.getBoolean(Clean_KEY);
		if(sdf)
		{
			Log.d("ibpd","nodata");
		}
		else
		{
			byte[] data = bundle.getByteArray(DATA_KEY);
			if(data==null){
				data=new byte[]{};
			}
			boolean ifmodify =  bundle.getBoolean(modify_KEY);
			if(ifmodify)//自定义显示
			{
				String s=new String(data);
				if(s!=null && s.length()>0){Log.d("ibpd",s);}

				String sdfs=  bundle.getString(String_key);
				if(!sdfs.isEmpty())
				{
					Log.d("ibpd","!sdfs.isEmpty()=true");
				}
			}else
			{
				boolean tagJudge = bundle.getBoolean(JUDGE_KEY);
				if (tagJudge)
				{
					String strdata = bundle.getString(DATA_KEY);
					if(strdata==null){
						Log.d("ibpd","tagJudge's data is null");
					}else {
						String receFormatData="{status:'99',data:'" + strdata + "'}";
						Log.d("ibpd", "tagJudge's data: " + receFormatData);
						webView.evaluateJavascript("dataReceive("+receFormatData+")", null);
					}
				}
				else
				{
					webView.evaluateJavascript("dataReceive({status:'0',data:'"+new String(data)+"'}",null);
//					boolean flagmove = bundle.getBoolean(move_KEY);
//
//					String s1=new String(data);
//
//					if(flagmove)//在同一个地方显示
//					{
//						Log.d("ibpd",s1);
//					}
//					else //往下移
//					{
//						Log.d("ibpd",s1);
//					}
				}
//				Log.d("ibpd","\n");
			}
			boolean proximity = bundle.getBoolean(PROXIMITY_KEY);
			if(proximity){
				// 获取标签ID（字节数组形式）
				byte[] tagId = bundle.getByteArray(TAG_ID);

				// 将字节数组转换为十六进制字符串
				StringBuilder tagIdStr = new StringBuilder();
				for (byte b : tagId) {
					tagIdStr.append(String.format("%02X", b));
				}
				// 显示标签信息
				String tagInfo =  "{tagId:'" + tagIdStr.toString()+"'}";
				webView.evaluateJavascript("nfcProximityEvent("+tagInfo+")",null);
			}
			boolean webdata_send = bundle.getBoolean(WEBDATA_SEND);
			if(webdata_send){
				byte[] dt = bundle.getByteArray(DATA_KEY);
				int len = bundle.getInt(DATA_LENKEY);
				new Thread(new Runnable() {
					@Override
					public void run() {
						Log.d("ibpd","MainActivity call sendData");
						MainActivity.demo.SendData(dt,len);
					}
				}).start();

			}
		}
	}
	public static String getrf_ndef_value_charmulti() {
//		return rf_EditCharMulti.getText().toString();
		return "1234567890abcdefg";
	}
	public static void Display_bytes(byte[] inbyte,int len)
	{
		Bundle bundle = new Bundle();
		bundle.putByteArray(DATA_KEY, inbyte);
		bundle.putBoolean(JUDGE_KEY, true);
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View layout = inflater.inflate(R.layout.fragment_webview, container, false);
		webView = layout.findViewById(R.id.webview);
		setupWebView();
		webView.loadUrl("http://192.168.32.69/");
		return layout;
	}



	public static void setAnswer(String answer) {	
		
		Bundle bundle = new Bundle();
		bundle.putByteArray(DATA_KEY, answer.getBytes());
		bundle.putBoolean(JUDGE_KEY, false);
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);
		
		
	}

	public static void setDatarateCallback(String datarate) {
			Bundle bundle = new Bundle();
			bundle.putByteArray(DATA_KEY, datarate.getBytes());
			bundle.putBoolean(JUDGE_KEY, false);
			Message msg = new Message();
			msg.setData(bundle);
			mHandler.sendMessage(msg);
	}

	public static void setDatarateSuccessCallback(String data) {
		Bundle bundle = new Bundle();
		bundle.putString(DATA_KEY, data);
		bundle.putBoolean(JUDGE_KEY, true);
		Message msg = new Message();
		msg.setData(bundle);
		mHandler.sendMessage(msg);
	}

public static void SendDatatoUart(CharSequence data)
{
	if (data.toString().equals(""))
	{
		//Toast.makeText(this, "data is null!!", 1000).show();
		setDatarateCallback("data is null!!");
		 return;
	}
	
	
	CharSequence t = data;
	char[] text = new char[t.length()];
	for (int i = 0; i < t.length(); i++) 
	{
		text[i] = t.charAt(i);
	}
	byte[] sd = new String(text).getBytes();
	
//	MainActivity.demo.SendData_call(sd,t.length());
	
//	Bundle bundle = new Bundle();
//	bundle.putByteArray(DATA_KEY, sd);
//	bundle.putInt(DATA_LENKEY, t.length());
//	Message msg = new Message();
//	msg.setData(bundle);
//	MainActivity.demo.mHandler1.sendMessage(msg);
	Bundle bundle = new Bundle();
	bundle.putBoolean(WEBDATA_SEND, true);
	bundle.putByteArray(DATA_KEY, sd);
	bundle.putInt(DATA_LENKEY, t.length());
	Message msg = new Message();
	msg.setData(bundle);
	mHandler.sendMessage(msg);
}	

}
